package com.sdry.web.controller.lz;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sdry.utils.PushExample;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.SpareParts;
import com.sdry.model.lz.SparePartsRepair;
import com.sdry.service.lz.SparePartsService;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;

/**
 * @ClassName SparePartsController
 * @Description 备品备件
 * @Author lz
 * @Date 2019年1月8日 09:41:51
 * @Version 1.0
 */
@Controller
@RequestMapping("/spareParts")
public class SparePartsController {
	
	public static final Integer AFFECT_ROW = 0;
	public static final String EXCEL_TITLE = "备品备件";
	@Resource
	SparePartsService sparePartsService;
	
	/**
	 * 备品备件添加
	 * @param response
	 * @param spareParts 备品备件实体
	 * @throws Exception
	 */
	@RequestMapping("/addSpareParts")
    public void addSpareParts(HttpServletResponse response, SpareParts spareParts) throws Exception {
    	if (spareParts != null) {
			if(StringUtil.isEmpty(spareParts.getInProductTime())){
				spareParts.setInProductTime(null);
			}
		}
        Long affectRow = sparePartsService.addSpareParts(spareParts);
        if (affectRow > AFFECT_ROW) {
            ResponseUtil.write(response, affectRow);
        } else {
            ResponseUtil.write(response, AFFECT_ROW);
        }
    }

	/**
	 * 备品备件维修登记
	 * @param response
	 * @param sparePartsRepair 备品备件维修实体
	 * @throws Exception
	 */
	@RequestMapping("/addSparePartsRepair")
    public void addSparePartsRepair(HttpServletResponse response, SparePartsRepair sparePartsRepair) throws Exception {
    	if (sparePartsRepair != null) {
			if(StringUtil.isEmpty(sparePartsRepair.getRepairStartTime())){
				sparePartsRepair.setRepairStartTime(null);
			}
			if(StringUtil.isEmpty(sparePartsRepair.getRepairEndTime())){
				sparePartsRepair.setRepairEndTime(null);
			}
		}
        Long affectRow = sparePartsService.addSparePartsRepair(sparePartsRepair);
        if (affectRow > AFFECT_ROW) {
        	List<SpareParts> spareParts = sparePartsService.querySparePartsByProductNo(sparePartsRepair.getProductNo());
        	sparePartsRepair.setProductCount("" + (Integer.parseInt(spareParts.get(0).getProductCount()) - Integer.parseInt(sparePartsRepair.getProductCount())));
        	Long affectRow2 = sparePartsService.updateSparePartsStatus(sparePartsRepair);
        	if((affectRow > AFFECT_ROW) && (affectRow2 > AFFECT_ROW)){
        		if(Integer.parseInt(spareParts.get(0).getProductCount()) < Integer.parseInt(spareParts.get(0).getRemark01())){
					int testSendPush = PushExample.testSendPush("库存数量不足", "库存数量不足", "", "0");
				}
        		ResponseUtil.write(response, affectRow);
        	}
        } else {
            ResponseUtil.write(response, AFFECT_ROW);
        }
    }

    /**
     * 单个删除和批量删除
     * @param response
     * @param idArr id数组
     * @throws Exception
     */
    @RequestMapping("/deleteSparePartsById")
    public void deleteSparePartsById(HttpServletResponse response, @RequestParam("idArr[]") String[] idArr) throws Exception {
        for (int i = 0; i < idArr.length; i++) {
            Long affectRow = sparePartsService.deleteSparePartsById(Long.parseLong(idArr[i]));
            if (affectRow > AFFECT_ROW) {
                ResponseUtil.write(response, affectRow);
            } else {
                ResponseUtil.write(response, AFFECT_ROW);
            }
        }
    }

    /**
     * 根据ID修改备品备件信息
     * @param response
     * @param spareParts 选中行的备品备件
     * @throws Exception
     */
    @RequestMapping("/editSparePartsById")
    public void editSparePartsById(HttpServletResponse response, SpareParts spareParts) throws Exception {
    	if (spareParts != null) {
			if(StringUtil.isEmpty(spareParts.getInProductTime())){
				spareParts.setInProductTime(null);
			}
		}
        Long affectRow = sparePartsService.editSparePartsById(spareParts);
        if (affectRow > AFFECT_ROW) {
            ResponseUtil.write(response, affectRow);
        } else {
            ResponseUtil.write(response, AFFECT_ROW);
        }
    }

    /**
     * 分页查询备品备件
     * @param criteria
     */
    @RequestMapping("/querySpareParts")
    public void querySpareParts(HttpServletResponse response, LzQueryCriteria criteria){
        String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        List<SpareParts> sparePartsList = sparePartsService.querySpareParts(criteria);
        //int count = samplekeepService.countSamplekeep(criteria);
        int count = sparePartsService.countSpareParts(criteria);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(sparePartsList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 分页查询备品备件维修
     * @param criteria
     */
    @RequestMapping("/querySparePartsRepair")
    public void querySparePartsRepair(HttpServletResponse response, LzQueryCriteria criteria){
        String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        List<SparePartsRepair> sparePartsList = sparePartsService.querySparePartsRepair(criteria);
        //int count = samplekeepService.countSamplekeep(criteria);
        int count = sparePartsService.countSparePartsRepair(criteria);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(sparePartsList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 页面加载时加载所有的备品备件
     * @param response
     */
    @RequestMapping("/queryAllSparePartsList")
    public void queryAllSparePartsList(HttpServletResponse response){
    	List<SpareParts> sparePartsList = sparePartsService.queryAllSparePartsList();
    	JSONArray jsonArray = JSONArray.fromObject(sparePartsList);
    	if(sparePartsList.size() > AFFECT_ROW){
    		try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	} else {
    		try {
				ResponseUtil.write(response, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    }
    
    /**
     * 根据备品备件编号查询对应的备品备件
     * @param response
     * @param productNo 备品备件编号
     */
    @RequestMapping("/querySparePartsByProductNo")
    public void querySparePartsByProductNo(HttpServletResponse response, String productNo){
    	List<SpareParts> spareParts = sparePartsService.querySparePartsByProductNo(productNo);
    	if(spareParts.size() > AFFECT_ROW){
    		JSONObject jsonObject = JSONObject.fromObject(spareParts.get(0));
    		try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	} else {
    		try {
				ResponseUtil.write(response, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    }
    
    /**
	 * 导出模板
	 * @return
     * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/exportFileMethod")
	public void ExportFileMethod(HttpServletResponse response) throws UnsupportedEncodingException {
		ExcelUtils.exportFile(EXCEL_TITLE, titleListTemplateMethod(), response);
	}
	
	/**
	 * 模板表头
	 * @return
	 */
	public List<String> titleListTemplateMethod(){
		List<String> list = new ArrayList<>();
		list.add("产品编号");
		list.add("产品名称");
		list.add("条形码");
		list.add("批次号");
		list.add("产品厂家");
		list.add("产品数量");
		list.add("安全库存");
		list.add("进货日期");
		return list;
	}
	
	/**
	 * EXCEL导入
	 * @param file EXCEL文件
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/uplodeFileMethod")
	public void importorMethod(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request, HttpServletResponse response) throws Exception{
		   //操作标识
		   int flag = 1; 
		   String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
		   File newFile = new File(savePath);
		   //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	       file.transferTo(newFile);
	       
	       //获取导入行数
	       List<String> names = titleListTemplateMethod();
	       int num = names.size();
	       
	       //取文件后缀
	       String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
	       
	       //文件数据
	       List<List<String>> lists = new ArrayList<>();
	       
	       //判断后缀
	       if(subfix.equals("xls")){
	    	   //调用方法读取信息
	    	   lists = ExcelUtils.readXls(savePath, request, num);
	 	   }else if(subfix.equals("xlsx")){
	 		   //调用方法读取信息
	 		   lists = ExcelUtils.readXlsx(savePath, request, num);
	 	   }else{
	 		    //文件不是excel
	 	   		flag = 2;
	 	   }
	       //文件是excel
	       if(flag == 1){
	    	   for (int i = 0; i < lists.size(); i++) {
	    		   SpareParts spareParts = listZhuanBeanMethod(lists.get(i));
		    	   Long affectRow = sparePartsService.addSpareParts(spareParts);
		    	   if (affectRow < AFFECT_ROW) {
		    		   flag = 0;
		    		   break;
		    	   }
		       }
	       }
	       response.getWriter().print(flag);
	}
	
	/**
	 * 集合转实体
	 * @param list
	 * @return
	 */
	public SpareParts listZhuanBeanMethod(List<String> list){
		SpareParts spareParts = new SpareParts();
		spareParts.setProductNo(list.get(0));
		spareParts.setProductName(list.get(1));
		spareParts.setBarCode(list.get(2));
		spareParts.setBatchNum(list.get(3));
		spareParts.setVender(list.get(4));
		spareParts.setProductCount(list.get(5));
		spareParts.setRemark01(list.get(6));
		spareParts.setInProductTime(list.get(7));
		return spareParts;
	}

	/**
	 * 安卓接口:查询库存预警值
	 * @param response
	 */
	@RequestMapping("/queryWarningStock")
	public void queryWarningStock(HttpServletResponse response) throws Exception {
		List<SpareParts> sparePartsList = sparePartsService.queryWarningStock();
		JSONObject jsonObject = new JSONObject();
		if(sparePartsList.size() > 0){
			jsonObject.put("state", 1);
			jsonObject.put("message", "成功");
			jsonObject.put("data", sparePartsList);
			ResponseUtil.write(response, jsonObject);
		} else {
			jsonObject.put("state", 0);
			jsonObject.put("message", "失败");
			jsonObject.put("data", "");
			ResponseUtil.write(response, jsonObject);
		}
	}
}